package jm.nj.demo22mian.sqlInject;

import jm.nj.demo22mian.utils.JdbcUitils;
import org.junit.Test;

import java.sql.*;

public class SqlInjectDemo {

    public void login(String username, String password) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        try {
            conn = JdbcUitils.getConnection();
            stmt = conn.createStatement();
            //其他
            //String sql = "SELECT * FROM USER WHERE username = '" + username + "' AND PASSWORD =" + " '" + password + "'";
            String sql = "SELECT * FROM USER WHERE username = '"+username+"' AND PASSWORD = '"+password+"'";
            rs = stmt.executeQuery(sql);
            if (rs.next()){
                System.out.println("登录成功");
            }else {
                System.out.println("登录失败");
            }


        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JdbcUitils.closeResource(conn,stmt,rs);
        }
    }

    /**
     * 预处理对象执行查询登录验证
     */
    public void login1(String username, String password) {
        Connection conn = null;
        //Statement stmt = null;
        PreparedStatement pstmt = null;//封装 使用
        ResultSet rs = null;

        try {
            conn = JdbcUitils.getConnection();
            //其他
            //String sql = "SELECT * FROM USER WHERE username = '" + username + "' AND PASSWORD =" + " '" + password + "'";
            String sql = "SELECT * FROM USER WHERE username = ? AND PASSWORD = ?";
            pstmt = conn.prepareStatement(sql);

            //单独设置参数
            pstmt.setString(1,username);
            pstmt.setString(2,password);
            rs = pstmt.executeQuery();

            if (rs.next()){
                System.out.println("登录成功");
            }else {
                System.out.println("登录失败");
            }


        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            JdbcUitils.closeResource(conn,pstmt,rs);
        }
    }




    @Test
    public void test(){
        String username = "tom";
        String password = "'  or  '1' = '1";
        login(username,password);
        login1(username,password);
    }


}
